<template>
  <div ref="Alph">
    <ul class="alpha">
      <li class="item" v-for="item of letters" :key="item" @click="change" @touchstart="touchStart"
      @touchmove="touchMove" @touchend="touchEnd" :ref="item"
      >{{item}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data: function () {
    return {
      isTouch: false,
      startY: 0,
      timer: null
    }
  },
  updated: function () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    change: function (e) {
      this.$emit('change', e.target.innerText)
    },
    touchStart: function () {
      this.isTouch = true
    },
    touchMove: function (e) {
      if (this.isTouch) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const moveY = e.touches[0].clientY
          const index = Math.floor((moveY - this.startY) / 15)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    touchEnd: function () {
      this.isTouch = false
    }
  },
  computed: {
    letters: function () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .alpha
    width: .4rem
    height: 100%
    line-height: .3rem
    position: absolute
    right: 0
    top: .1.58rem
    bottom: 0
    display: flex
    flex-direction:column
    justify-content: center
    font-size: .18rem
    color: $bgColor
    .item
      text-align: center
</style>
